package com.neo.debade.web.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings({ "serial" })
public class Captcha extends HttpServlet {

	private int width = 55;

	private int height = 20;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/* 输出response参数设置 */
		response.setContentType("image/gif");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		/* 生成验证码 */
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics graphics = image.getGraphics();
		graphics.setColor(new Color(0, 198, 233));
		graphics.fillRect(0, 0, width, height);
		graphics.setFont(new Font("Verdana", Font.BOLD, 16));
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(new Random().nextInt(10));
			sRand += rand;
			graphics.setColor(new Color(255, 255, 255));
			graphics.drawString(rand, 11 * i + 3, 16);
		}
		graphics.dispose(); // 必须调用dispose将设置绘制到图片上
		/* 将验证数字放入session */
		request.getSession().setAttribute("VALID_CODE", sRand);
		/* 将生成图片流输出 */
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

}
